package com.lym.order.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lym.common.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

/**
 * 自定义限流异常处理器
 */
@Component //注册到spring容器中
public class MyBlockExceptionHandler implements BlockExceptionHandler {

    /**
     * JSON格式的返回
     * 这是SpringMVC底层整合jackson的一个工具类，用于将java对象转换为json格式的字符串
     */
    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 处理限流异常
     *
     * @param request
     * @param response
     * @param resourceName
     * @param e
     * @throws Exception
     */
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       String resourceName, BlockException e) throws Exception {

//        response.setStatus(429); //too many requests
        response.setContentType("application/json;charset=utf-8");

        PrintWriter writer = response.getWriter();

        R error = R.error("too many requests", resourceName + " 被Sentinel限制了，原因：" + e.getClass());

        String json = objectMapper.writeValueAsString(error);
        writer.write(json);

        writer.flush();
        writer.close();
    }

}
